package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.SupplierBean;
import com.project.mapper.ISupplierMapper;
import com.project.service.ISupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SupplierServiceImp implements ISupplierService {
    @Autowired
    private ISupplierMapper supplierMapper;
    @Override
    public IPage<SupplierBean> findByItem(Integer pageNO, String scope, String name) {
        QueryWrapper<SupplierBean> query = new QueryWrapper<>();
        if (scope != null && !scope.equals("")) {
            query.like("s_scope", scope);
        }
        if (name!= null &&!name.equals("")) {
            query.like("s_name", name);
        }
        return supplierMapper.selectPage(new Page<>(pageNO,3),query);
    }

    @Override
    public SupplierBean findById(Integer id) {
        return supplierMapper.selectById(id);
    }

    @Override
    public void update(Integer supplierId, String newHeadName, String newPhone) {
        SupplierBean supplier = supplierMapper.selectById(supplierId);
        if (newHeadName!= null && !newHeadName.equals("")) {
            supplier.setHeadName(newHeadName);
        }
        if (newPhone!= null && !newPhone.equals("")) {
            supplier.setHeadPhone(newPhone);
        }
        supplierMapper.updateById(supplier);
    }

    @Override
    public void add(SupplierBean supplierBean) {
        QueryWrapper<SupplierBean> qw = new QueryWrapper<>();
        qw.eq("s_name", supplierBean.getSupplierName());
        SupplierBean sp = supplierMapper.selectOne(qw);
        if (sp == null) {
            supplierMapper.insert(supplierBean);
        }
    }

    @Override
    public void batchAdd(List<SupplierBean> suppList) {
        if (suppList.size() > 0) {
            for (int i = 0; i < suppList.size(); i++) {
                QueryWrapper<SupplierBean> qw = new QueryWrapper<>();
                qw.eq("s_name", suppList.get(i).getSupplierName());
                //判断每一个供应商在表中是否存在
                SupplierBean sp = supplierMapper.selectOne(qw);
                //如果不存在进行循环添加
                if (sp == null) {
                    supplierMapper.insert(suppList.get(i));
                }
            }
        }
    }

    @Override
    public List<SupplierBean> findAll() {
        return supplierMapper.selectList(null);
    }
}
